<?php

declare (strict_types=1);

namespace app\middleware;

use Closure;
use think\App;
use think\Env;
use think\facade\Config;
use think\Request;
use think\Response;

class CustomEnv
{
    protected App $app;

    protected Env $env;

    public function __construct(App $app, Env $env)
    {
        $this->app = $app;
        $this->env = $env;
    }

    /**
     * 自定义数据库配置初始化加载
     * @access public
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $rootPath = $this->app->getRootPath();
        if (!file_exists($rootPath . '.env') && is_file($rootPath . 'application.env')) {
            $this->env->load($rootPath . 'application.env');
            // 重新加载数据库配置
            $configPath = $this->app->getConfigPath();
            $files = [];
            if (is_dir($configPath)) {
                $files = [
                    $configPath . 'database' . $this->app->getConfigExt()
                ];
            }
            foreach ($files as $file) {
                $this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
            }
        }
        return $next($request);
    }
}